
import os
import sys
import ConfigParser
from Singleton import Singleton

def cur_file_dir():
    path = sys.path[0]
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)

class ConfigService(Singleton):
    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.items = {}
        
    def readConfigFile(self, filename):
        self.config.read(filename)
        #s = self.config.sections()  
        #print 'section:', s  
        options = self.config.options("ini")  
        
        for option in options :
            value = self.config.get('ini', option)
            self.items[option] = value
            
        return self.items
    
    def getItems(self, filename):
        if len(self.items.keys()) <= 0 :
            self.items = self.readConfigFile(filename)
        return self.items
        
    def setConfigFile(self):
        for k, v in self.items.items() :
            self.config.set('ini', k, v)
        curPath = cur_file_dir()
#        if __name__ == 'Utils.ConfigService':
#            curPath += '/..'
        self.config.write(open(curPath+'/conf/config.ini', "w"))
        
    def getValue(self, option):
        curPath = cur_file_dir()
#        if __name__ == 'Utils.ConfigService':
#            curPath += '/..'
        return self.getItems(curPath+'/conf/config.ini')[option]
    
    def setValue(self, option, value):
        self.items[option] = value
    
    def setItems(self, items):
        self.items = items
          
          
if __name__ == '__main__':
    conf = ConfigService()
    print conf.getValue("db_source")
    SDN = "PROVIDER=%s;\
    DATA SOURCE=%s;\
    Persist Security Info=%s;\
    Jet OLEDB:Database Password=%s"%(
                                     conf.getValue("db_provider"),
                                     conf.getValue("db_source"),
                                     conf.getValue("db_security_info"),
                                     conf.getValue("db_code")
                                     )
    print SDN
    
    code = eval((conf.getValue("mach_set")))
    for id in xrange(1,17):
        if code&0x01:
            print id
        code >>= 1

    port = conf.getValue("mq_port")
    print int(port)